package service

import (
	"context"
	"github.com/google/uuid"
	"log"
	"strconv"
	__ "video-srv/basic/proto"
	"video-srv/handler/model"
	"video-srv/pkg"
)

type Server struct {
	__.UnimplementedVideoServer
}

func (s *Server) AddVideo(_ context.Context, in *__.AddVideoReq) (*__.AddVideoResp, error) {
	var video model.Video

	video = model.Video{
		Title:    in.Title,
		Category: in.Category,
		Tags:     in.Tags,
		CoverUrl: in.CoverUrl,
		VideoUrl: in.VideoUrl,
	}
	err := video.AddVideo()
	if err != nil {
		return nil, err
	}

	var protobuf model.Protobuf

	protobuf = model.Protobuf{
		VideoId:       int32(video.Id),
		ProtobufViews: "无",
	}

	err = protobuf.AddProtobuf()
	if err != nil {
		return nil, err
	}

	return &__.AddVideoResp{VideoId: int64(video.Id)}, nil
}

func (s *Server) ProtobufVideo(_ context.Context, in *__.ProtobufVideoReq) (*__.ProtobufVideoResp, error) {

	var protobuf model.Protobuf

	err := protobuf.FindProtobufContentByVideoId(int(in.VideoId))
	if err != nil {
		return nil, err
	}

	protobuf.ProtobufId = int32(in.ProtobufId)
	protobuf.ProtobufContent = int8(in.ProtobufContent)
	protobuf.ProtobufViews = in.ProtobufViews

	videoToken := uuid.NewString()

	err = protobuf.HandleProtobuf()
	if err != nil {
		return nil, err
	}

	log.Println(videoToken)

	var video model.Video

	err = video.FindVideoId(int(in.VideoId))
	if err != nil {
		return nil, err
	}

	video.Status = protobuf.ProtobufContent
	err = video.UpdateVideo()
	if err != nil {
		return nil, err
	}

	return &__.ProtobufVideoResp{ProtobufId: int64(protobuf.Id)}, nil
}

func (s *Server) FindVideo(_ context.Context, in *__.FindVideoReq) (*__.FindVideoResp, error) {
	var video model.Video

	list, err := video.FindVideoList()
	if err != nil {
		return nil, err
	}

	var videoList []*__.VideoList
	for _, v := range list {
		listV := &__.VideoList{
			VideoId:  int64(v.Id),
			Title:    v.Title,
			Category: v.Category,
			Tags:     v.Tags,
			CoverUrl: v.CoverUrl,
			VideoUrl: v.VideoUrl,
		}
		pkg.Md5(strconv.Itoa(int(v.Id)))
		videoList = append(videoList, listV)
	}

	return &__.FindVideoResp{List: videoList}, nil
}
